package org.jmc.refmanager.web.wicket.page.admin;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.domain.service.UserManager;
import org.jmc.refmanager.util.Util;
import org.jmc.refmanager.web.wicket.markup.html.navigation.paging.CustomPagingNavigator;
import org.jmc.refmanager.web.wicket.page.panel.ConfirmDeletePanel;
import org.jmc.refmanager.web.wicket.page.template.TemplatePage;

import com.sun.java.swing.plaf.nimbus.EditorPanePainter;

/**
 */
@AuthorizeInstantiation(value={"ROLE_ADMIN", "ROLE_APPROVER"})
public class UserFindPage extends TemplatePage {

	private ModalWindow confirmModal;
	
	@SpringBean(name="userManager")
	private UserManager userManager;

	/**
	 * @param parameters
	 */
	public UserFindPage(PageParameters parameters) {
		super(parameters);
		initComponents(parameters.getString("matricule"));
	}

	public UserFindPage() {
		super();
		initComponents(null);
	}
	
	private void initComponents(String matricule) {
		add(new Label("pageTitle", "Recherche d'un utilisateur"));
		
		confirmModal = new ModalWindow("confirmModal");
        // Style graphique : CSS_CLASS_GRAY ou CSS_CLASS_BLUE
		confirmModal.setCssClassName(ModalWindow.CSS_CLASS_BLUE);
        // Type du masque : TRANSPARENT ou SEMI_TRANSPARENT
		confirmModal.setMaskType(ModalWindow.MaskType.TRANSPARENT);
		confirmModal.setTitle("Confirmation");
		confirmModal.setInitialWidth(400);
		confirmModal.setWidthUnit("px");
		confirmModal.setResizable(false);
		confirmModal.setUseInitialHeight(false);
		
		add(confirmModal);
		
		UserSearchForm form = new UserSearchForm("formUserFind");
		add(form);
        final FeedbackPanel feedback = new FeedbackPanel("feedback", 
        		new ComponentFeedbackMessageFilter(form));
        add(feedback);
        
        SortableUserDataProvider dp = new SortableUserDataProvider(matricule);
        final DataView<User> dataView = new DataView<User>("userRow", dp) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(final Item<User> item) {
				final User user = item.getModelObject();
				item.add(new Label("matricule", user.getMatricule()));
				OrgUnit validationScope = user.getValidationScope();
				String scope = validationScope==null?"N/A":validationScope.getLibCourt();
				item.add(new Label("scope", String.valueOf(scope)));
				item.add(new Label("roleName", user.getRole().getDescription()));

				Link<Integer> editLink = new Link<Integer>("editLink", new PropertyModel<Integer>(user, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick() {
						PageParameters params = new PageParameters();
						params.add("id", getDefaultModelObjectAsString());
						
						setResponsePage(UserEditPage.class, params);
						
					}
				};
				item.add(editLink);
				
				AjaxLink<Integer> deleteLink = new AjaxLink<Integer>("deleteLink", 
													new PropertyModel<Integer>(user, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick(final AjaxRequestTarget ajaxRequestTarget) {
						confirmModal.setContent(						
						new ConfirmDeletePanel(confirmModal.getContentId(), 
								String.format("Etes vous sûr de supprimer l'utilisateur '%s'?", user.getMatricule())) {
							private static final long serialVersionUID = 1L;

							@Override
							protected void onConfirm() {
								Integer userId = getModelObject();
								userManager.remove(userId);
								info("L'utilisateur a été supprimé avec succès");
							}
						});
						// Desactivation du message lie au post et changement de fenetre
						ajaxRequestTarget.appendJavascript( "Wicket.Window.unloadConfirmation = false;" ); 
						confirmModal.show(ajaxRequestTarget);
					}
				};
				
				item.add(deleteLink);
			}

			@Override
		    public boolean isVisible() {
				return this.getItemCount() > 0;
			}
		};

		dataView.setItemsPerPage(20);

		add(new OrderByBorder("orderByMatricule", "matricule", dp) {
			private static final long serialVersionUID = 1L;

			@Override
            protected void onSortChanged() {
                dataView.setCurrentPage(0);
            }
        });

		add(new OrderByBorder("orderByRoleName", "role", dp) {
			private static final long serialVersionUID = 1L;

			@Override
            protected void onSortChanged() {
                dataView.setCurrentPage(0);
            }
        });
		
		add(dataView);
		add(new CustomPagingNavigator("navigator", dataView) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
		        return dataView.getItemCount() > 0;
		    }
		});
	}

	/**
	 * 
	 * Formulaire de recherche
	 *
	 */
	final class UserSearchForm extends Form<String> {
		private static final long serialVersionUID = 1L;
		private String matricule;

		public UserSearchForm(String id) {
			super(id);
	        add(new TextField<String>("txtMatricule", new PropertyModel<String>(this, "matricule")));
	        add(new Button("btnSearch") {

				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				/* (non-Javadoc)
				 * @see org.apache.wicket.markup.html.form.Button#onSubmit()
				 */
				@Override
				public void onSubmit() {
					PageParameters params = new PageParameters();
					params.add("matricule", getMatricule());
					setResponsePage(UserFindPage.this.getClass(), params); 
				}
	        	
	        });
	        add(new Button("btnAdd") {
				private static final long serialVersionUID = 1L;

				/* (non-Javadoc)
				 * @see org.apache.wicket.markup.html.form.Button#onSubmit()
				 */
				@Override
				public void onSubmit() {
					// Lien vers la page de creation d'utilisateur
					setResponsePage(UserAddPage.class);
				}
	        });
		}

		@Override
		protected void onSubmit() {
			if (!Util.isEmptyOrBlank(getMatricule())) {
				info(String.format("Recherche des utilisateurs dont le matricule est '%s'",
					getMatricule()));
			}
		}

		/**
		 * @return the matricule
		 */
		public String getMatricule() {
			return matricule;
		}

		/**
		 * @param matricule the matricule to set
		 */
		public void setMatricule(String matricule) {
			this.matricule = matricule;
		}
	}
}

